package summer.tree;

public class Solution654 {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return construct(nums, 0, nums.length - 1);
    }

    public TreeNode construct(int[] nums, int start, int end) {
        if (start > end) return null;
        int index = findMaxIndex(nums, start, end);
        TreeNode root = new TreeNode(nums[index]);
        root.left = construct(nums, start, index - 1);
        root.right = construct(nums, index + 1, end);
        return root;
    }

    public int findMaxIndex(int[] nums, int start, int end) {
        int index = end;
        for (int i = start; i < end; i++) {
            if (nums[i] > nums[index]) index = i;
        }
        return index;
    }
}
